// 搜索框
let searchContents = document.querySelectorAll('.header-search input');
for(let i = 0; i < searchContents.length; i++) {
	let searchContent = searchContents[i];
	let searchButton = searchContent.nextElementSibling;
	searchButton.onclick = function() {
		let searchValue = searchContent.value.trim();
		if(searchValue) {
			location.href = '/page/user/search/list.html?keyword=' + searchValue;
		} else if(searchContent.placeholder != '搜索商品') {
			location.href = '/page/user/search/list.html?keyword=' + searchContent.placeholder;
		}
	}
	searchContent.onkeydown = function(e) {
		e = e || window.event;
		if(e.keyCode == 13 || e.keyCode == 108) {
			// 回车键
			searchButton.click();
		}
	}
}
let cartTh = document.getElementById('cartTh'); // 购物车头部
let cartTb = cartTh.nextElementSibling; // 购物车数据部分
let cartAmount = cartTh.parentNode.previousElementSibling.querySelector('.goods-count'); // 全部商品
let cartTf = cartTb.nextElementSibling; // 购物车底部
let cartSum = document.getElementById('cartSum'); // 合计
let thSelectAll = cartTh.querySelector('input[type=checkbox]'); // 购物车顶部全选复选框
let tfSelectAll = cartTf.querySelector('input[type=checkbox]'); // 购物车底部全选复选框
let cartChks = cartTb.querySelectorAll('input[type=checkbox'); // 购物车内所有的复选框，进行删除操作后，要重新获取
let balance = cartTf.querySelector('.tf-balance'); // 预约按钮
let tfDelete = cartTf.querySelector('.tf-delete'); // 购物车底部删除按钮
let mask = document.getElementById('mask');
let cartMask = document.querySelector('.cart-nodata-mask');
let set = new Set(); // 用来存放选中的购物车项
ajax({
	type: 'POST',
	async: false,
	url: '/cart/myCart',
	success: function(xhr) {
		let arg = JSON.parse(xhr.responseText);
		if(arg.code == 3020) {
			location.replace('/page/user/login.html');
		} else if(arg.code == 200) {
			let dataArray = arg.data;
			if(!dataArray || dataArray.length == 0) {
				return;
			}
			// 隐藏无数据图片
			let cartMask = cartTh.parentNode.nextElementSibling.nextElementSibling;
			cartMask.style.display = 'none';
			/* 设置全部商品的数目 */ 
			cartAmount.innerText = dataArray.length;
			let cartTbUl = cartTb.children[0];
			dataArray.forEach((data) => {
				let li = document.createElement('li');
				li.className = 'cart-item';
				let _imgPath = data.goods.imgPath;
				let imgPathIndex = _imgPath.indexOf(';')
				if(imgPathIndex != -1) {
					// 若有多张图则取第一张
					_imgPath = "//127.0.0.1:8080" + _imgPath.substring(0, imgPathIndex);
				}
				li.innerHTML = `<div class="fl tb-select">
									<input type="checkbox" />
								</div>
								<div class="fl tb-info">
									<div class="fl tb-info-l">
										<img src="${_imgPath}" alt="商品图片" />
									</div>
									<div class="fl">
										<em>${data.goods.name}</em>
										<p>${data.goods.details}</p>
										<div class="goods-label">
										</div>
									</div>
								</div>
								<div class="fl tb-price">
									<span>${data.goods.realPrice}</span>
								</div>
								<div class="fl tb-amount">
									<button style="cursor: pointer">-</button>
									<input type="text" value="${data.count}" disabled="disabled"/>
									<button style="cursor: pointer">+</button>
								</div>
								<div class="fl tb-sum">
									<span>${data.realSubtotal}</span>
								</div>
								<div class="fl tb-op">
									<a href="javascript:void(0);">删除</a>
								</div>`;
				let goodsLabel = li.querySelector('.goods-label');
				let labels = data.goods.label.split('####TPL####');
				labels.forEach((label) => {
					let labelDiv = document.createElement('div');
					labelDiv.innerText = label;
					goodsLabel.appendChild(labelDiv);
				});
				let checkbox = li.querySelector('input[type=checkbox]');
				checkbox.addEventListener('click', () => {
					if(checkbox.checked) {
						set.add(data.goods.gid + '#' + data.cartId);
					} else {
						set.delete(data.goods.gid + '#' + data.cartId);
					}
				});
				let plusButton = li.querySelectorAll('button')[1];
				let reduceButton = li.querySelectorAll('button')[0];
				let freeCount = data.goods.count - data.goods.reservedCount;
				setButtonStyle(plusButton, reduceButton, freeCount);
				plusButton.onclick = function() {
					if(this.style.cursor == 'pointer') {
						ajax({
							type: 'POST',
							async: true,
							url: '/cart/amount',
							data: {
								id1: data.cartId,
								id2: data.goods.gid,
								type: '1'
							},
							beforeSend: function() {
								// 显示等待图片
								mask.style.display = 'block';
								mask.style.backgroundColor = 'rgba(0, 0, 0, 0)';
								mask.innerHTML = `<div class="mask-wrap" style="position: absolute; top: 50%; left: 50%; margin-top: -45px;margin-left: -45px;width: 90px;height: 90px;background: url(/images/loading2.gif) no-repeat;background-size: 90px;">
												  </div>`;
							},
							success: function(xhr) {
								removeAllChildren(mask);
								mask.style.display = 'none';
								let arg = JSON.parse(xhr.responseText);
								if(arg.code == 3020) {
									location.replace('/page/user/login.html');
								} else if(arg.code == 3110 || arg.code == 3201) {
									toast('系统繁忙，请刷新后重试');
								} else if(arg.code == 200) {
									location.reload(true);
								}
							}
						});
					}
				}
				reduceButton.onclick = function() {
					if(this.style.cursor == 'pointer') {
						ajax({
							type: 'POST',
							async: true,
							url: '/cart/amount',
							data: {
								id1: data.cartId,
								id2: data.goods.gid,
								type: '0'
							},
							beforeSend: function() {
								// 显示等待图片
								mask.style.display = 'block';
								mask.style.backgroundColor = 'rgba(0, 0, 0, 0)';
								mask.innerHTML = `<div class="mask-wrap" style="position: absolute; top: 50%; left: 50%; margin-top: -45px;margin-left: -45px;width: 90px;height: 90px;background: url(/images/loading2.gif) no-repeat;background-size: 90px;">
												  </div>`;
							},
							success: function(xhr) {
								removeAllChildren(mask);
								mask.style.display = 'none';
								let arg = JSON.parse(xhr.responseText);
								if(arg.code == 3020) {
									location.replace('/page/user/login.html');
								} else if(arg.code == 3110 || arg.code == 3110) {
									toast('系统繁忙，请刷新后重试');
								} else if(arg.code == 200) {
									location.reload(true);
								}
							}
						});
					}
				}
				let deleteButton =li.querySelector('.tb-op a');
				deleteButton.onclick = function() {
					let priceEle = deleteButton.parentNode.parentNode.querySelector('.tb-sum span');
					// 弹出提示框
					deleteCartItemToast('是否删除该商品？', () => {
						removeAllChildren(mask);
						mask.style.display = 'none';
						// 向后端发送删除请求
						ajax({
							type: 'POST',
							async: true,
							url: '/cart/delete',
							data: {
								id1: data.cartId,
								id2: data.goods.gid
							},
							success: function(xhr) {
								let arg = JSON.parse(xhr.responseText);
								if(arg.code == 3020) {
									location.replace('/page/user/login.html');
								} else if(arg.code == 3110) {
									toast('系统繁忙，请刷新后重试');
								} else if(arg.code == 200) {
									if(checkbox.checked) {
										set.delete(data.goods.gid + '#' + data.cartId);
									}
									toast('删除成功', '#84cc77');
									removeWorld(li);
									// 重新获取cartChks，进行删除操作后要重新获取
									cartChks = cartTb.querySelectorAll('input[type=checkbox');
									// 购物车内的总商品数-1
									cartAmount.innerText = Number(cartAmount.innerText) - 1;
									// 获取购物车内被选中商品的数量
									let count = 0;
									for(let i = 0; i < cartChks.length; i++) {
										if(cartChks[i].checked) {
											count++;
										}
									}
									// 判断该商品有没有被选中
									if(checkbox.checked) {
										// 重新设置总价钱
										let price = Number(priceEle.innerText);
										let sumEle = cartSum.children[1];
										let sum = Number(sumEle.innerText);
										sum = sum * 100 - price * 100;
										console.log(sum);
										if(sum == 0) {
											sum = '0.00';
										}
										sumEle.innerText = parseFloat(sum / 100).toFixed(2);
										// 重新设置已选商品有多少件
										cartTf.querySelector('.tf-amount em').innerText = count;
										// 若没有选中的商品则设置预约按钮为默认效果
										if(count == 0) {
											balance.style.backgroundColor = '#b0b0b0';
											balance.style.cursor = 'not-allowed';	
										}
									} else {
										// 若该商品没有被选中，判断剩下的商品是否全部都被选中了
										if(count == cartChks.length) {
											thSelectAll.checked = 'checked';
											tfSelectAll.checked = 'checked';
										}
									}
									// 判断是否全部删除，若全部删除则显示无数据图片
									if(cartTb.children[0].children.length == 0) {
										cartMask.style.display = 'block';
									}
								}
							}
							
						});
					});	
				}
				cartTbUl.appendChild(li);
			});
		}
	}
});


// 重新获取购物车内所有的复选框
cartChks = cartTb.querySelectorAll('input[type=checkbox');
/*
	功能：设置加减按钮的样式 
*/
function setButtonStyle(plusButton, reduceButton, freeCount) {
	let count = Number(reduceButton.nextElementSibling.value);
	if(count == freeCount || count > freeCount) {
		plusButton.style.cursor = 'default';
		plusButton.style.color = '#ccc';
	}
	if(count == 1) {
		reduceButton.style.cursor = 'default';
		reduceButton.style.color = '#ccc';
		
	}
}

/*
	功能：删除按钮点击时页面弹出框效果
	参数1：弹出框里提示的文字
	参数2：删除功能的实现函数
*/

function deleteCartItemToast(deleteTip, deleteEvent) {
	mask.style.display = 'block';
	mask.innerHTML = `<div class="mask-wrap" style="position: absolute; top: 50%; left: 50%; margin-top: -73.5px;margin-left: -200px;width: 400px;height: 147px;box-sizing: border-box;border-radius: 4px;padding: 16px 20px;overflow: hidden; background-color: #fff;">
						<div class="mask-h clearfix">
							<span style="float: left;font-size: 18px;color: #23ade5;">删除</span>
							<span style="float: right;width: 24px;height: 24px;background: url(/images/x_icon.png) no-repeat;cursor: pointer;" title="关闭面板" ></span>
						</div>
						<div class="mask-content" style="padding: 20px 0; font-size: 14px;">${deleteTip}</div>
						<div class="mask-b">
							<button class="mask-button mask-button-cancel" style="float: right; margin-right: 4px;">取消</button>
							<button class="mask-button" style="float: right; margin-right: 12px;">确定</button>
						</div>
					  </div>`;
	let maskH = mask.querySelector('.mask-h');
	maskH.children[1].onclick = function() {
		removeAllChildren(mask);
		mask.style.display = 'none';
	}
	let maskB = mask.querySelector('.mask-b');
	maskB.children[0].onclick = function() {
		removeAllChildren(mask);
		mask.style.display = 'none';
	}
	maskB.children[1].onclick = deleteEvent;
}
for(let i = 0; i < cartChks.length; i++) {
	// 给购物车里面的复选框设置选中效果和非选中效果
	let chk = cartChks[i];
	chk.onclick = function() {
		let li = this.parentNode.parentNode;
		let priceEle = li.querySelector('.tb-sum span');
		let price = Number(priceEle.innerText);
		let sumEle = cartSum.children[1];
		let sum = Number(sumEle.innerText);
		// 获得总共选中的商品数目
		let count = 0;
		for(let j = 0; j < cartChks.length; j++) {
			if(cartChks[j].checked) {
				count++;
			}
		}
		cartTf.querySelector('.tf-amount em').innerText = count;
		// 设置背景色、计算总价钱、是否是全选状态
		if(chk.checked) {
			li.style.backgroundColor = 'rgba(84, 158, 197, .2)';
			sum = sum * 100 + price * 100;
			sumEle.innerText = parseFloat(sum / 100).toFixed(2);
			if(count == cartChks.length) {
				thSelectAll.checked = 'checked';
				tfSelectAll.checked = 'checked';
			}
			balance.style.backgroundColor = '#549ec5';
			balance.style.cursor = 'pointer';	
		} else {
			li.style.backgroundColor = '#fcfcfc';
			sum = sum * 100 - price * 100;
			if(sum == 0) {
				sum = '0.00';
			}
			sumEle.innerText = parseFloat(sum / 100).toFixed(2);
			thSelectAll.checked = '';
			tfSelectAll.checked = '';
			if(count == 0) {
				balance.style.backgroundColor = '#b0b0b0';
				balance.style.cursor = 'not-allowed';	
			}
		}
	}
}
/*
	功能：设置全选效果
*/
function selectAll() {
	let sumEle = cartSum.children[1];
	let _other = (this == thSelectAll) ? tfSelectAll : thSelectAll; 
	if(this.checked) {
//		let sum = 0; // 总价格
//		// 设置li选中效果
//		for(let i = 0; i < cartChks.length; i++) {
//			let chk = cartChks[i];
//			let li = chk.parentNode.parentNode;
//			if(!chk.checked) {
//				chk.checked = 'checked';
//				li.style.backgroundColor = 'rgba(84, 158, 197, .2)';
//			}
//			let priceEle = li.querySelector('.tb-sum span');
//			let price = Number(priceEle.innerText);
//			sum = sum + price;
//		}
//		// 设置总价钱
//		sumEle.innerText = sum;
//		cartTf.querySelector('.tf-amount em').innerText = cartChks.length;
//		// 设置另一个全选按钮的全选效果
//		_other.checked = 'checked';
//		// 预约按钮效果
//		balance.style.backgroundColor = '#549ec5';
//		balance.style.cursor = 'pointer';	
		for(let i = 0; i < cartChks.length; i++) {
			let chk = cartChks[i];
			if(!chk.checked) {
				chk.click();
			}
		}
	} else {
		// 设置li默认效果
//		for(let i = 0; i < cartChks.length; i++) {
//			let chk = cartChks[i];
//			let li = chk.parentNode.parentNode;
//			if(chk.checked) {
//				chk.checked = '';
//				li.style.backgroundColor = '#fcfcfc';
//			}
//		}
//		// 设置总价钱为0.00
//		sumEle.innerText = '0.00';
//		// 设置已选商品为0件
//		cartTf.querySelector('.tf-amount em').innerText = 0;
//		// 取消另一个全选按钮的选中效果
//		_other.checked = '';
//		// 设置预约按钮为默认效果
//		balance.style.backgroundColor = '#b0b0b0';
//		balance.style.cursor = 'not-allowed';
		for(let i = 0; i < cartChks.length; i++) {
			let chk = cartChks[i];
			if(chk.checked) {
				chk.click();
			}
		}
	}
}
thSelectAll.onclick = selectAll;
tfSelectAll.onclick = selectAll;
/* 设置页面滚动效果 

	功能：解决获取页面滚动距离兼容性问题

function getScrollTop() {
	return document.body.scrollTop || document.documentElement.scrollTop;
}
const specialLoc = cartTb.offsetTop + cartTb.offsetHeight - 593;
function scrollEvent() {
	let scrollTop = getScrollTop();
	if(scrollTop > specialLoc) {
		cartTf.style.position = 'relative';
	} else {
		cartTf.style.position = 'fixed';
	}
}
// 页面加载时判断滚动距离
scrollEvent();
document.onscroll = scrollEvent;*/
/* 设置购买按钮效果 */
balance.onclick = function() {
	if(this.style.cursor == '' || this.style.cursor == 'not-allowed' ) {
		this.children[1].style.display = 'block';
	} else {
		let param = [...set].join('$');
		ajax({
			type: 'POST',
			async: true,
			url: '/order/addByCart',
			data: {
				param: param
			},
			beforeSend: function() {
				// 显示等待图片
				mask.style.display = 'block';
				mask.style.backgroundColor = 'rgba(0, 0, 0, 0)';
				mask.innerHTML = `<div class="mask-wrap" style="position: absolute; top: 50%; left: 50%; margin-top: -45px;margin-left: -45px;width: 90px;height: 90px;background: url(/images/loading2.gif) no-repeat;background-size: 90px;">
								  </div>`;
			},
			success: function(xhr) {
				removeAllChildren(mask);
				mask.style.display = 'none';
				let arg = JSON.parse(xhr.responseText);
				if(arg.code == 3020) {
					location.replace('/page/user/login.html');
				} else if(arg.code == 3110) {
					toast('系统繁忙，请刷新后重试');
				} else if(arg.code == 200) {
					location.href = '/page/user/buy/order.html?' + arg.data;
				} else if(arg.code == 3300) {
					console.log(arg.message);
					toast(arg.message);
				} else if(arg.code == 3101) {
					toast('请先完善您的个人信息');
				}
			}
		});
	}
}
balance.onmouseleave = function() {
	if(this.children[1].style.display == 'block') {
		setTimeout(() => {
			this.children[1].style.display = 'none';
		}, 500);
	}
}

/* 设置点击底部的删除按钮事件 */
tfDelete.onclick = function() {
	// 弹出提示框
	let deleteCount = 0;
	let deleteTip = '请选择要删除的商品！';
	for(let j = 0; j < cartChks.length; j++) {
		if(cartChks[j].checked) {
			deleteCount++;
			deleteTip = '是否删除选中的商品？';
			break;
		}
	}
	deleteCartItemToast(deleteTip, () => {
		removeAllChildren(mask);
		mask.style.display = 'none';
		if(deleteCount > 0) {
			// 获取参数
			let param = [...set].join('$');
			// 清空set集合
			set.clear();
			ajax({
				type: 'POST',
				async: false,
				url: '/cart/deletes',
				data: {
					param: param
				},
				success: function(xhr) {
					let arg = JSON.parse(xhr.responseText);
					if(arg.code == 3020) {
						location.replace('/page/user/login.html');
					} else if(arg.code == 3110) {
						toast('系统繁忙，请刷新后重试');
					} else if(arg.code == 200) {
						toast('删除成功', '#84cc77');
						for(let j = 0; j < cartChks.length; j++) {
							if(cartChks[j].checked) {
								// 删除
								let cartItem = cartChks[j].parentNode.parentNode;
								removeWorld(cartItem);
							}
						}
						// 重新获取cartChks，进行删除操作后要重新获取
						cartChks = cartTb.querySelectorAll('input[type=checkbox');
						let sumEle = cartSum.children[1];
						// 设置总价钱
						sumEle.innerText = '0.00';
						// 设置预约按钮为默认效果
						balance.style.backgroundColor = '#b0b0b0';
						balance.style.cursor = 'not-allowed';
						// 设置已选商品为0件
						cartTf.querySelector('.tf-amount em').innerText = 0;	
						// 重新设置购物车里的商品数量
						cartAmount.innerText = cartChks.length;
						// 判断是否全部删除，若全部删除则显示无数据图片
						if(cartTb.children[0].children.length == 0) {
							cartMask.style.display = 'block';
						}
					}
				}
			});
			
		}
	});	
}